import React, {Component} from 'react';
import {Map, Marker} from 'react-amap';
import {
    Form,
    Input,
    Button,
    Row,
    Col,
    Upload,
    InputNumber,
    message,
} from 'antd';
import {LoadingOutlined, PlusOutlined, CloseCircleOutlined} from '@ant-design/icons';

import PageTitle from "@src/components/PageTitle";
import Ckeditor from '@src/components/ckeditor/Ckeditor';
import axios from '@src/lib/axios';

const {Search} = Input;

export default class ActAddOrEdit extends Component {
    constructor() {
        super();
        this.toolEvents = {
            created: (tool) => {
                this.tool = tool;
            }
        };
        this.form = React.createRef();
        this.state = {
            id: '',
            data: {
                "hotel_name": "",
                "image_ids": "",
                "merchants_phone": "",
                "product_desc": "",
                "stock": "",
                "platform_price": "",
                "settlement_price": "",
                "market_price": "",
                "rebate_m_percent": "",
                "rebate_c_percent": "",
                "spell_limits": "0",
                "virtual_limits": "",
                "tag": "",
                "sort_value": "",
                "merchants_name": "",
                "merchants_address": "",
                "x": "",
                "y": ""
            },
            imageList: [],
            mapPlugins: ['ToolBar'],
            mapCenter: {longitude: 116.407526, latitude: 39.904030},
            markerPosition: {longitude: 116.407526, latitude: 39.904030},
            tmp_longitude: "",
            tmp_latitude: "",
            img_server:`${process.env.IMG_SERVER_URL}`
        }

    }

    onFinish = (value) => {
        Object.assign(this.state.data, value);
        let imageIds = [];
        let {data, imageList} = this.state;
        console.log(imageList);
        imageList.forEach(function (item) {
            imageIds.push(item.imgid)
        });
        data.image_ids = imageIds.join(',');
        axios.post("/activity/hot/product/add", data).then(res => {
            message.success(res.msg);
            this.props.history.push('/activity/package');
        }).catch(res => {
            console.log(res)
        });
    }


    ckReadyHandler = (instan, vk) => {
        instan.setData(this.form.current.getFieldValue(vk));
    };

    ckChangeHandler = (k, instan) => {
        this.form.current.setFieldsValue({[k]: instan.getData()});
    };


    handleChange = (res) => {
        console.log('res', res)
        let {file} = res;
        if (file.status == "done") {
            let imageItem = {
                uid: file.uid,
                imgid: file.response.data.imgid,
            }
            this.state.imageList.push(imageItem)
        }
    }

    handlePreview = ({fileList}) => {
        console.log(fileList)
    }
    onRemove = (file) => {
        console.log('remove:', file)
        let {imageList} = this.state
        this.setState({imageList: imageList.filter(item => item.uid !== file.uid)})
    }

    //拾取商家地理位置坐标
    geoCode = (address) => {
        axios.post('/map/geo_code',{address}).then(res=>{
            if (res.code === 0) {
                let {data} = res
                this.setState({
                    mapCenter: {longitude: data[0], latitude: data[1]},
                    markerPosition: {longitude: data[0], latitude: data[1]},
                    tmp_longitude:data[0],
                    tmp_latitude:data[1]
                })
                this.form.current.setFieldsValue({x: data[0]})
                this.form.current.setFieldsValue({y: data[1]})
                message.success("ok")
            }else{
                message.warning("dfasdfas")
            }

        }).catch(res=>{
            console.log(res)
        });
    };


    changeCenter = (value) => {
        let {tmp_longitude, tmp_latitude} = this.state
        if (tmp_longitude && tmp_latitude) {
            this.setState({
                mapCenter: {longitude: tmp_longitude, latitude: tmp_latitude},
                markerPosition: {longitude: tmp_longitude, latitude: tmp_latitude}
            })
        }
    };

    //经度
    xOnchange = (value) => {
        this.setState({tmp_longitude:value.target.value});
    }
    //纬度
    yOnchange = (value) =>{
        this.setState({tmp_latitude:value.target.value});
    }

    render() {

        let ck1 = '';

        const uploadBtn = (
            <div>
                <PlusOutlined/>上传
            </div>
        )

        const uploadProps = {
            name: "userfile",
            action: "/images_serv/",
            listType: "picture-card",
            onRemove: this.onRemove,
            onChange: this.handleChange
        }


        return (
            <div style={{padding: '0 0 100px 15px', background: '#fff'}}>
                <PageTitle title={'添加产品'} showBack/>
                <Form
                    ref={this.form}
                    labelAlign={"right"}
                    name={"activity_product"}
                    onFinish={this.onFinish}
                    labelCol={{span: 2}}
                    wrapperCol={{span: 20}}
                    initialValues={this.state.data}
                >
                    <Row className="fields-box">
                        <Col span={24}>
                            <Form.Item
                                label="产品名称"
                                name="product_name"
                                rules={[{required: true, message: '请输入产品名称!'}]}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item
                                label="商家电话"
                                name={"merchants_phone"}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item
                                label="产品图片">
                                <Upload {...uploadProps}>
                                    {this.state.imageList.length > 5 ? null : uploadBtn}
                                </Upload>
                            </Form.Item>
                            <Form.Item
                                label="产品描述"
                                name="product_desc"
                                rules={[
                                    {required: true, message: '产品描述必须填写！'}
                                ]}
                            >
                                <Ckeditor editorId="kids" readyHandler={(instan) => {
                                    ck1 = instan;
                                    this.ckReadyHandler(instan, 'product_desc')
                                }} changeHandler={(instan) => this.ckChangeHandler('product_desc', instan)}></Ckeditor>
                            </Form.Item>
                            <Row className="fields-box">
                                <Col span={6} style={{paddingLeft: 45}}>
                                    <Form.Item
                                        labelCol={1}
                                        label="库存"
                                        name="stock"
                                        rules={[
                                            {required: true, message: "库存必须填写"}
                                        ]}
                                    >
                                        <InputNumber/>
                                    </Form.Item>
                                </Col>
                                <Col span={6}>
                                    <Form.Item
                                        labelCol={1}
                                        label="平台价"
                                        name="platform_price"
                                        rules={[
                                            {required: true, message: "平台价必须填写"}
                                        ]}
                                    >
                                        <InputNumber min={1} max={999}/>
                                    </Form.Item>
                                </Col>
                                <Col span={6}>
                                    <Form.Item
                                        labelCol={1}
                                        label="结算价"
                                        name="settlement_price"
                                        rules={[
                                            {required: true, message: "结算价必须填写"}
                                        ]}
                                    >
                                        <InputNumber min={1} max={999}/>
                                    </Form.Item>
                                </Col>
                                <Col span={6}>
                                    <Form.Item
                                        labelCol={1}
                                        label="市场价"
                                        name={"market_price"}
                                        rules={[
                                            {required: true, message: "市场价必须填写"}
                                        ]}
                                    >
                                        <InputNumber/>
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={6}>
                                    <Form.Item
                                        labelCol={1}
                                        label="分销商返佣"
                                        name="rebate_m_percent"
                                        rules={[
                                            {required: true, message: "不能为空"}
                                        ]}
                                    >
                                        <InputNumber min={1} max={999} suffix={"%"}/>
                                    </Form.Item>
                                </Col>
                                <Col span={6}>
                                    <Form.Item
                                        labelCol={1}
                                        label="普通用户返佣"
                                        name={"rebate_c_percent"}
                                        rules={[
                                            {required: true, message: "不能为空"}
                                        ]}
                                    >
                                        <InputNumber min={1} max={999} suffix={"%"}/>
                                    </Form.Item>
                                </Col>
                                <Col span={6}>
                                    <Form.Item
                                        labelCol={1}
                                        label="最低成团数"
                                        name={"spell_limits"}
                                        rules={[
                                            {required: true, message: "不能为空"}
                                        ]}
                                    >
                                        <InputNumber min={1} max={999}/>
                                    </Form.Item>
                                </Col>
                                <Col span={6}>
                                    <Form.Item
                                        labelCol={1}
                                        label="虚拟成功拼团数"
                                        name={"virtual_limits"}
                                    >
                                        <InputNumber/>
                                    </Form.Item>
                                </Col>
                            </Row>

                            <Form.Item
                                label={"产品标签"}
                                name={"tag"}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item
                                label={"排序值"}
                                name={"sort_value"}
                            >
                                <InputNumber/>
                            </Form.Item>
                            <Form.Item
                                label={"商家名称"}
                                name={"merchants_name"}
                            >
                                <Input/>
                            </Form.Item>

                            <Form.Item
                                label={"商家地址"}
                                name={"merchants_address"}
                            >
                                <Search
                                    placeholder="输入商家地址：省+市+区+县+街道+门牌号"
                                    onSearch={value => this.geoCode(value)}
                                    enterButton="拾取商家地理坐标"
                                    style={{width: 500}}
                                />
                            </Form.Item>
                            <Input.Group>
                                <Form.Item
                                    label={"经度"}
                                    name={"x"}
                                >
                                    <Input onChange={value => this.xOnchange(value)} style={{width: "20%"}}/>
                                </Form.Item>
                                <Form.Item
                                    label={"纬度"}
                                    name={"y"}
                                >
                                    <Input onChange={value => this.yOnchange(value)} style={{width: "20%"}}/>
                                </Form.Item>
                                <Row>
                                    <Col>
                                        <Button type="link" href={"https://lbs.amap.com/console/show/picker"} target={"_blank"}>去高德地图坐标拾取器获取经纬度</Button>
                                        <Button size={"small"} type="primary" name={"2332"} onClick={() => this.changeCenter()}>点我查看定位</Button>
                                    </Col>
                                </Row>
                            </Input.Group>
                        </Col>
                    </Row>
                    <Form.Item label="所在位置如图">
                        <Row style={{width: '100%', height: 400}}>
                            <Col span={24}>
                                <Map amapkey='4545b8cd5b830357e075e88eb7f336be' zoom={14} plugins={this.state.mapPlugins} center={this.state.mapCenter}>
                                    <Marker position={this.state.markerPosition} />
                                </Map>
                            </Col>
                        </Row>
                    </Form.Item>
                    <Row>
                        <Col span={6} push={6}>
                            <Button style={{float: "right"}} type="primary" htmlType="submit">确认</Button>
                        </Col>
                    </Row>
                </Form>


            </div>
        )
    }
}